package com.zy.dao.impl;

import com.zy.dao.AddToCarDao;
import com.zy.utils.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AddToCarDaoImpl implements AddToCarDao {

    @Override
    public boolean addToCar(int userId, int shopId) {
        String checkSql = "SELECT quantity FROM tb_car WHERE user_id = ? AND shop_id = ?";
        String updateSql = "UPDATE tb_car SET quantity = quantity + 1 WHERE user_id = ? AND shop_id = ?";
        String insertSql = "INSERT INTO tb_car (user_id, shop_id, quantity, unit_price) SELECT ?, ?, 1, price FROM tb_shops WHERE id = ?";
        try (Connection connection = JdbcUtil.getConnection();
             PreparedStatement checkStmt = connection.prepareStatement(checkSql);
             PreparedStatement updateStmt = connection.prepareStatement(updateSql);
             PreparedStatement insertStmt = connection.prepareStatement(insertSql)) {
            checkStmt.setInt(1, userId);
            checkStmt.setInt(2, shopId);
            ResultSet rs = checkStmt.executeQuery();
            if (rs.next()) {
                updateStmt.setInt(1, userId);
                updateStmt.setInt(2, shopId);
                return updateStmt.executeUpdate() > 0;
            } else {
                insertStmt.setInt(1, userId);
                insertStmt.setInt(2, shopId);
                insertStmt.setInt(3, shopId);
                return insertStmt.executeUpdate() > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
